

<template>
  <div class="container">
    <div class="stepList">
      <el-steps :active="active" align-center>
        <el-step title="上传文件" description="上传溯源数据表"></el-step>
        <el-step title="数据导入" description="数据导入成功后筛选"></el-step>
        <el-step title="导入完成" description="数据导入成功"></el-step>
      </el-steps>
    </div>
    <!-- 步骤一 导入数据 -->
    <div v-show="div1" class="upload">
      <el-upload
        ref="upload"
        class="upload-demo"
        action=""
        drag
        :on-preview="handlePreview"
        :on-remove="handleRemove"
        :on-change="uploads"
        :file-list="fileList"
        :limit="1"
        accept=".xlsx"
        :auto-upload="false"
      >
        <i class="el-icon-upload"></i>
        <div class="el-upload__text"><em>上传溯源数据表</em></div>
        <div class="el-upload__tip" slot="tip">
          文件后缀名必须为xls或xlsx(Excel格式)
        </div>
      </el-upload>
      <el-button type="primary" style="margin-top: 20px" @click="next">下一步</el-button>
    </div>
    <!-- 步骤二 筛选错误的数据 -->
    <div v-show="div2">
      <!-- 导入数据结果展示 -->
      <div style="display: flex; justify-content: center; align-items: center">
        <div style="margin-right:20px;">
          <el-alert
            title="本次可导入数据数量"
            type="success"
            :description="this.successCount"
            :closable="false"
          />
        </div>
        <div>
          <el-alert
            title="本次不可导入数据数量"
            type="error"
            :description="this.errorCount"
            :closable="false"
          />
        </div>
      </div>
      <!-- 不可导入数据列表 -->
      <div id="failList">
        <span>不可导入数据列表</span>
        <el-button type="warning" plain @click="downLoad">导出</el-button>
      </div>
      <div class="failTableList">
        <el-table
          id="exportTab"
          :data="tableData"
          border
          style="width: 100%"
        >
          <el-table-column prop="error" label="错误提示"/>
          <el-table-column prop="name" label="姓名" />
          <el-table-column prop="id_card" label="身份证号" />
          <el-table-column prop="entrance" label="入学口" />
          <el-table-column
            prop="student_registration_number"
            label="学籍注册号"
          />
        </el-table>
      </div>
      <div class="failBtn" style="margin:20px 0;">
        <el-button @click="back">上一步</el-button>
        <el-button @click="submitUpload">导入数据</el-button>
      </div>
    </div>
    <!-- 步骤三 导入成功 -->
    <div v-show="div3" class="upload">
      <el-alert
        title="批量导入完成"
        type="success"
        :description="`成功导入资源数量：${successCount}`"
        show-icon
      />
    </div>
    <div style="text-align:center;">
      <el-button v-show="show6" style="margin-top: 12px" @click="complete">完成</el-button>
    </div>
  </div>
</template>
<script>
import XLSX from "xlsx";
import FileSaver from "file-saver";
export default {
    name:'UploadTable',
  data() {
    return {
      active: 1,
      show3: false,
      show4: true,
      show5: false,
      show6: false,
      div1: true,
      div2: false,
      div3: false,
      successCount: "0",
      errorCount: "0",
      tableData: [],
      fileList: [],
      id_card_data: [],
      srn_data: [],
      tableData1: [],
      studentSource: [], //符合导入条件的数据
    };
  },
  methods: {
    next() {
      if (this.fileList.length == 0) {
        this.$message.error('请选择文件上传');
      } else {
        this.active = 2;
        this.div1 = false;
        this.div2 = true;
      }
    },
    back() {
      this.active = 1;
      this.div1 = true;
      this.div2 = false;
    },
    submitUpload() {
      if (++this.active > 1) {
        this.show3 = true;
        this.show4 = false;
        if (this.active === 2) {
          this.show5 = true;
          this.div2 = true;
          this.div1 = false;
          this.div3 = false;
        }
        if (this.active === 3) {
          this.show6 = true;
          this.show5 = false;
          this.show3 = false;
          this.div2 = false;
          this.div1 = false;
          this.div3 = true;
        }
      }
      var studentSource=JSON.stringify(this.studentSource)
      // console.log(studentSource)
      this.$post('dataCenter/uploadStudentSource', {
        studentSource
      }).then((r) => {

      })
    },
    uploads(file, fileList) {
      const files = { 0: file.raw };
      if (!this.readExcel1(files)) {
        for (var i = 0; i < fileList.length; i++) {
          if (file.name === fileList[i].name) {
            fileList.splice(i, 1);
          }
        }
      }
      this.fileList = fileList;
    },
    isCardNo(card) {
      // 身份证号码为15位或者18位，15位时全为数字，18位前17位为数字，最后一位是校验位，可能为数字或字符X
      var reg = /(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/;
      if (reg.test(card) === false) {
        return false;
      }
      return true;
    },
    readExcel1(files) {
      
      // 表格导入
      if (files.length <= 0) {
        // 如果没有文件名
        return false;
      } else if (!/\.(xls|xlsx)$/.test(files[0].name.toLowerCase())) {
        // this.fileList.splice(0, 1)
        alert("上传格式不正确，请上传xls或者xlsx格式");
        return false;
      }

      const fileReader = new FileReader();
      fileReader.onload = (ev) => {
        try {
          const data = ev.target.result;
          const workbook = XLSX.read(data, {
            type: "binary",
          });
          this.studentSource=[]
          //清空不可导入数据表格的数据
          this.tableData=[]
          const wsname = workbook.SheetNames[0]; // 取第一张表
          const ws = XLSX.utils.sheet_to_json(workbook.Sheets[wsname]); // 生成json表格内容
          for (var i = 0; i < ws.length; i++) {
            this.studentSource.push(ws[i])
          }

          for (var i = 0; i < ws.length; i++) {
            ws[i]["error"] = "";
            if (!ws[i].name) {
              if (ws[i]["error"] === "" && this.tableData.includes(ws[i]) == false) {
                this.tableData.push(ws[i]);

              }
              ws[i]["error"] += "名字不能为空 ";
              delete this.studentSource[i]
              // this.studentSource.splice(i,1)
            }
            if (!ws[i].entrance) {
              if (ws[i]["error"] === "" && this.tableData.includes(ws[i]) == false) {
                this.tableData.push(ws[i]);

              }
              ws[i]["error"] += "入学口不能为空 ";
              // this.studentSource.splice(i,1)
              delete this.studentSource[i]
            }
            if (!this.isCardNo(ws[i].id_card)) {
              //去除身份证号空格和回车
              // w[i].id_card.replace(/\ +/g,"");
              // w[i].id_card.replace(/[\r\n]/g,"");
              if (ws[i]["error"] === "" && this.tableData.includes(ws[i]) == false) {
                this.tableData.push(ws[i]);
              }
              ws[i]["error"] += "身份证号位数不对 ";
              // this.studentSource.splice(i,1)
              delete this.studentSource[i]
            }
            this.id_card_data.push(ws[i].id_card)
            this.srn_data.push(ws[i].student_registration_number)
          }
          //校验身份证号重复
          var id_card_data = this.id_card_data
            this.$post('dataCenter/selectRepeatIdCard', {
              id_card_data
            }).then((r) => {
              var duplicateElements=r.data.data
              for (var i = 0; i < ws.length; i++) {
                for (var j = 0; j < duplicateElements.length; j++) {
                  if(ws[i].id_card == duplicateElements[j] && this.tableData.includes(ws[i]) == false){
                    ws[i]["error"] = "身份证号重复";
                    this.tableData.push(ws[i]);
                    delete this.studentSource[i]
                  }

                }
              }
              
            })

            //校验学籍注册号
            var srn_data = this.srn_data
            this.$post('dataCenter/selectRepeatStudentRegistrationNumber', {
              srn_data
            }).then((r) => {
              var duplicateElements1=r.data.data
              for (var i = 0; i < ws.length; i++) {
                for (var j = 0; j < duplicateElements1.length; j++) {
                  if(ws[i].student_registration_number == duplicateElements1[j] && this.tableData.includes(ws[i]) == false){
                    ws[i]["error"] = "学籍注册号重复";
                    this.tableData.push(ws[i]);
                    delete this.studentSource[i]
                  }
                }
              }
              // try {
              //   this.successCount = ws.length - this.tableData.length + "条";
              //   this.errorCount = this.tableData.length + "条";
              // } catch (err) {
              //   console.log(err);
              // }
            })
            try {
                this.successCount = ws.length - this.tableData.length + "条";
                this.errorCount = this.tableData.length + "条";
              } catch (err) {
                console.log(err);
              }
          this.$refs.upload.value = "";
        } catch (e) {
          return false;
        }
      };
      fileReader.readAsBinaryString(files[0]);
      
      return true;
    },
    complete() {
      this.$refs.upload.submit();
      this.active = 1;
      this.div1 = true;
      this.div2 = false;
      this.div3 = false;
    },
    handleRemove(file, fileList) {
      this.tableData = [];
    },
    downLoad(file, fileList) {
      this.exportExcel();
    },
    exportExcel() {
      var xlsxParam = { raw: true }; // 导出的内容只做解析，不进行格式转换
      var wb = XLSX.utils.table_to_book(
        document.querySelector("#exportTab"),
        xlsxParam
      );
      var wbout = XLSX.write(wb, {
        bookType: "xlsx",
        bookSST: true,
        type: "array",
      });
      try {
        FileSaver.saveAs(
          new Blob([wbout], { type: "application/octet-stream" }),
          "错误数据.xlsx"
        );
      } catch (e) {
        if (typeof console !== "undefined") {
          console.log(e, wbout);
        }
      }
      return wbout;
    },
    handlePreview(file) {
      console.log(file);
    },
  },
};
</script>
<style scoped>
.upload {
  border-radius: 5px;
  min-height: 36px;
  justify-content: center;
  align-items: center;
}
.container {
  padding: 20px;
  background-color: #ffffff;
}
.stepList {
  width: 80%;
  margin: 30px auto;
}
.upload {
  width: 400px;
  margin: 20px auto;
  padding-bottom: 50px;
}
#failList {
  display: flex;
  justify-content: space-between;
  margin: 10px 0;
}
#failList .failBtn {
  padding-top: 10px;
  padding-bottom: 50px;
}
</style>
